package com.xiaouyudeguang.common.filter;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xiaouyudeguang.common.config.AppConfig;
import com.xiaouyudeguang.common.constants.Headers;
import com.xiaouyudeguang.common.utils.StringUtils;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class WebFilter extends  OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        String uuid = request.getHeader(Headers.TRACE_ID);
        if (StringUtils.isBlank(uuid)) {
            uuid = IdWorker.get32UUID().substring(0, AppConfig.getEnv().getProperty("spring.application.name", "application").length());
        }
        MDC.put(Headers.TRACE_ID, uuid);
        filterChain.doFilter(request, response);
    }
}
